package cn.superchart.module.dev.install.service.impl;

import cn.superchart.common.base.BaseServiceImpl;
import cn.superchart.module.dev.install.entity.ScInstall;
import cn.superchart.module.dev.install.mapper.ScInstallMapper;
import cn.superchart.module.dev.api.pojo.ScInstallParam;
import cn.superchart.module.dev.api.ScInstallService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

@Slf4j
@Service
public class ScInstallServiceImpl extends BaseServiceImpl<ScInstall, ScInstallMapper> implements ScInstallService {

    String fileName = "init.txt";

    @Override
    public boolean installed(ScInstallParam scInstallParam) {
        return setInitFile(scInstallParam.getSalt());
    }


    private Boolean setInitFile(String content){
        boolean isOk = false;
        if(!verify()){
            try {
                // 获取项目根目录路径
                String rootPath = System.getProperty("user.dir");
                log.info("项目根目录: {}", rootPath);
                // 在根目录创建文件
                File file = new File(rootPath, fileName);
                if (!file.exists()) {
                    isOk = file.createNewFile(); // 创建文件
                    log.info("文件已创建：{} 创建结果{}", file.getAbsolutePath(),isOk);
                } else {
                    log.info("文件已存在：{}", file.getAbsolutePath());
                }
                // 写入内容到文件
                try (FileWriter writer = new FileWriter(file)) {
                    writer.write(content);
                    log.info("文件内容已写入:{}",content);
                }
            } catch (IOException e) {
                log.error("写入文件异常:{}",e.getMessage());
            }
            return isOk;
        }
        return false;
    }


    @Override
    public Boolean verify() {
        String rootPath = System.getProperty("user.dir");
        File file = new File(rootPath, fileName);
        return file.exists();
    }
}
